package com.yzh.booksystem.controller;

import com.yzh.booksystem.entity.Book;
import com.yzh.booksystem.service.UpdateService;
import com.yzh.booksystem.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "UpdateServlet",urlPatterns = "/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String bookname = request.getParameter("bookname");
        float price = Float.parseFloat(request.getParameter("price"));
        String address = request.getParameter("address");
        String isbn = request.getParameter("isbn");
        Book book = new Book();
        book.setBookname(bookname);
        book.setPrice(price);
        book.setAddress(address);
        book.setIsbn(isbn);

        UpdateService updateService = new UpdateService();
        UserService userService = new UserService();
        HttpSession session = request.getSession();
        try {
            if (updateService.isUpdate(book)) {
                try {
                    List<Book> listBooks = userService.total_books_show();
                    session.setAttribute("listBooks", listBooks);
                    response.setHeader("refresh", "2; url=/booksystem/index.jsp");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            } else {
                response.sendRedirect("/booksystem/edit.jsp?error3=yes");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
